﻿#include "JZCoNetwork.h"
#include "JZCo.h"

JZCoNetworkReply::JZCoNetworkReply(QNetworkReply* reply)
{
	m_reply = reply;
}

void JZCoNetworkReply::waitFinish()
{
	while (!m_reply->isFinished())
		jzco_sleep(20);
}

QByteArray JZCoNetworkReply::read()
{
	QByteArray buffer;    
	while (!m_reply->isFinished())
	{
		if (m_reply->bytesAvailable() > 0)
		{
			buffer = m_reply->readAll();
			break;
		}
		else
		{
			jzco_sleep(20);
		}
	}
	return buffer;
}

QByteArray JZCoNetworkReply::readToEnd()
{
	QByteArray buffer;
	while (!m_reply->isFinished())
		jzco_sleep(20);

	buffer = this->m_reply->readAll();
	return buffer;
}

//JZCoTcpSocket
JZCoTcpSocket::JZCoTcpSocket()
{
	m_socket = nullptr;
}

JZCoTcpSocket::JZCoTcpSocket(QTcpSocket* socket)
{
	m_socket = socket;
}

bool JZCoTcpSocket::isNull()
{
	return !m_socket;
}

QTcpSocket* JZCoTcpSocket::socket()
{    
	return m_socket;
}

bool JZCoTcpSocket::connectToHost(const QString& addr, quint16 port)
{
	bool ret = false;
	m_socket->connectToHost(addr, port);
	while (true)
	{
		if (m_socket->state() == QTcpSocket::HostLookupState 
			|| m_socket->state() == QTcpSocket::ConnectingState)
		{
			jzco_sleep(20);
		}
		else
		{
			ret = (m_socket->state() == QTcpSocket::ConnectedState);
			break;
		}
	}
	return ret;
}

void JZCoTcpSocket::disconnectFromHost()
{
	m_socket->disconnectFromHost();
	while(m_socket->state() == QTcpSocket::ClosingState)
		jzco_sleep(10);
}

bool JZCoTcpSocket::waitForReadyRead(int timeout)
{
    QElapsedTimer t;
    t.start();
    while (m_socket->state() == QTcpSocket::ConnectedState)
    {
        if (m_socket->bytesAvailable() > 0)
            return true;
        else if (t.elapsed() > timeout)
            return false;
        else
            jzco_sleep(20);
    }
    return false;
}

QByteArray JZCoTcpSocket::read(int size)
{
	QByteArray buffer;
	int remain_size = size;
	while (m_socket->state() == QTcpSocket::ConnectedState)
	{
		if (m_socket->bytesAvailable() > 0)
		{
			QByteArray read = m_socket->read(remain_size);
			buffer.append(read);
			remain_size -= read.size();
			if (remain_size == 0)
				break;
		}
		else
		{
			jzco_sleep(20);
		}
	}
	return buffer;
}

QByteArray JZCoTcpSocket::readAll()
{
	QByteArray buffer;
	while (m_socket->state() == QTcpSocket::ConnectedState)
	{
		if (m_socket->bytesAvailable() > 0)
		{
			buffer = m_socket->readAll();
			break;
		}
		else
		{
			jzco_sleep(20);
		}
	}
	return buffer;
}

qint64 JZCoTcpSocket::write(const QByteArray& buffer)
{
	return m_socket->write(buffer);
}

//JZCoTcpServer
JZCoTcpServer::JZCoTcpServer(QTcpServer* server)
{
	m_server = server;
}

JZCoTcpSocket JZCoTcpServer::accept()
{
	QTcpSocket* socket = nullptr;
	while (m_server->isListening())
	{
		if (m_server->hasPendingConnections())
		{
			socket = m_server->nextPendingConnection();
			break;
		}
		else
		{
			jzco_sleep(20);
		}
	}
	return JZCoTcpSocket(socket);
}